package engine.util.shader;

import java.nio.FloatBuffer;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBShaderObjects;
import org.lwjgl.opengl.ARBVertexShader;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;

public class Shader {

	private Shader() {};
	
	public static boolean shadersAvailable() {
		String str = GL11.glGetString(GL11.GL_VERSION);
		
		int version = Integer.parseInt(str.substring(0, 1));
		
		return version >= 2;
	}
	
	public static void useShader(int program) {
		ARBShaderObjects.glUseProgramObjectARB(program);
	}
	
	public static void disableShader() {
		ARBShaderObjects.glUseProgramObjectARB(0);
	}
	
	public static void get(int shader, String name) {
		FloatBuffer buf = BufferUtils.createFloatBuffer(4);
		int loc = ARBShaderObjects.glGetUniformLocationARB(shader, name);
		ARBShaderObjects.glGetObjectParameterARB(shader, loc, buf);
		
		for(int i = 0; i < buf.capacity(); i++) {
			System.out.print(buf.get(i));
		}
		System.out.println();
	}
	
	public static void sendUniform1i(int program, String name, int parameter) {
		int loc = -1;
		loc = ARBShaderObjects.glGetUniformLocationARB(program, name);
		if(loc != -1) {
			ARBShaderObjects.glUniform1iARB(loc, parameter);
		} else {
			System.out.println(name + " not found!");
		}
	}
	
	public static void sendUniform1f(int program, String name, float parameter) {
		int loc = -1;
		loc = ARBShaderObjects.glGetUniformLocationARB(program, name);
		if(loc != -1) {
			ARBShaderObjects.glUniform1fARB(loc, parameter);
		} else {
			System.out.println(name + " not found!");
		}
	}
	
	public static void sendUniform2f(int program, String name, float x, float y) {
		int loc = -1;
		loc = ARBShaderObjects.glGetUniformLocationARB(program, name);
		if(loc != -1) {
			ARBShaderObjects.glUniform2fARB(loc, x, y);
		} else {
			System.out.println(name + " not found!");
		}
	}
	
	public static void sendUniform3f(int program, String name, float x, float y, float z) {
		int loc = -1;
		loc = ARBShaderObjects.glGetUniformLocationARB(program, name);
		if(loc != -1) {
			ARBShaderObjects.glUniform3fARB(loc, x, y, z);
		} else {
			System.out.println(name + " not found!");
		}
	}
	
	public static void sendUniform4f(int program, String name, float x, float y, float z, float w) {
		int loc = -1;
		loc = ARBShaderObjects.glGetUniformLocationARB(program, name);
		if(loc != -1) {
			ARBShaderObjects.glUniform4fARB(loc, x, y, z, w);
		} else {
			System.out.println(name + " not found!");
		}
	}
	
	public static int attributeLocation(int program, String attribute) {
		return GL20.glGetAttribLocation(program, attribute);
	}
	
	public static void glVertexAttrib1f(int location, float value) {
		ARBVertexShader.glVertexAttrib1fARB(location, value);
	}
}
